package com.gengzp.system.facade.impl;

import com.gengzp.common.enums.GenderEnum;
import com.gengzp.common.exception.BusinessException;
import com.gengzp.common.model.user.entity.SysUser;
import com.gengzp.common.model.user.resp.SearchSysUserCountResp;
import com.gengzp.common.utils.ThreadUtils;
import com.gengzp.permission.utils.PermissionUtils;
import com.gengzp.system.facade.SysUserFacade;
import com.gengzp.system.mapper.SysUserMapper;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @ClassName SysUserFacadeImpl
 * @Description 系统角色模块门面层实现类
 * @Author gengzp
 * @Date 2025/9/8 20:33
 */
@Service
public class SysUserFacadeImpl implements SysUserFacade {

    @Autowired
    private SysUserMapper sysUserMapper;

    /**
     * 用户token缓存key前缀
     */
    private static final String USER_TOKEN_CACHE_KEY_PREFIX = "permission:user_token:";

    @Override
    public SysUser searchSysUserById(Long userId) {
        if (Objects.isNull(userId)) {
            throw BusinessException.get("用户id不能为空");
        }

        if (Objects.equals(userId, Long.valueOf(PermissionUtils.getSuperAdminUserId()))) {
            return buildSuperAdminSysUser();
        }

        return sysUserMapper.selectSysUserById(userId);
    }

    @Override
    public List<SysUser> fuzzySearchSysUsersByNickname(String nickname) {
        if (StringUtils.isBlank(nickname)) {
            throw BusinessException.get("用户昵称不能为空");
        }

        List<SysUser> sysUsers = sysUserMapper.fuzzySelectSysUserByNickname(nickname);
        if (PermissionUtils.getSuperAdminNickname().contains(nickname)) {
            sysUsers.add(buildSuperAdminSysUser());
        }

        return sysUsers;
    }

    @Override
    public SysUser searchSysUserByNickname(String nickname) {
        if (StringUtils.isBlank(nickname)) {
            throw BusinessException.get("用户昵称不能为空");
        }
        if (Objects.equals(PermissionUtils.getSuperAdminNickname(), nickname)) {
            return buildSuperAdminSysUser();
        }

        return sysUserMapper.selectSysUserByNickname(nickname);
    }

    @Override
    public List<SysUser> searchSysUsersByIds(List<Long> userIds) {
        if (CollectionUtils.isEmpty(userIds)) {
            return Lists.newArrayList();
        }

        List<SysUser> sysUsers = sysUserMapper.selectSysUsersByIds(userIds);
        if (userIds.contains(Long.valueOf(PermissionUtils.getSuperAdminUserId()))) {
            sysUsers.add(buildSuperAdminSysUser());
        }

        return sysUsers;
    }

    @Override
    public Map<Long, String> searchSysUserId2NicknameMapByIds(Collection<Long> userIds) {
        List<SysUser> sysUsers = searchSysUsersByIds(new ArrayList<>(userIds));
        if (CollectionUtils.isEmpty(sysUsers)) {
            return Maps.newHashMap();
        }

        return sysUsers.stream().collect(Collectors.toMap(SysUser::getId, SysUser::getUserNickname));
    }

    @Override
    public SearchSysUserCountResp searchSysUserCount() {
        SearchSysUserCountResp resp = new SearchSysUserCountResp();

        List<String> errorMessages = ThreadUtils.batchExecute(() -> {
            // 查询系统用户总数量
            resp.setSysUserCount(sysUserMapper.selectSysUserCount());
        }, () -> {
            // 查询一周内发生过修改的用户
            resp.setOneStarSysUserModifiedCount(
                    sysUserMapper.selectSysUserCountByLastModifiedTimeStart(
                            new Date(System.currentTimeMillis() - 7 * 24 * 60 * 60 * 1000L)));
        });

        if (CollectionUtils.isNotEmpty(errorMessages)) {
            throw BusinessException.get(StringUtils.join(errorMessages, "；"));
        }

        return resp;
    }

    /**
     * 组装超级管理员系统用户信息
     *
     * @return 系统用户信息
     */
    private SysUser buildSuperAdminSysUser() {
        SysUser sysUser = new SysUser();
        sysUser.setId(Long.valueOf(PermissionUtils.getSuperAdminUserId()));
        sysUser.setUserIntroduction("系统超级管理员");
        sysUser.setUserNickname(PermissionUtils.getSuperAdminNickname());
        sysUser.setUserAccount(PermissionUtils.getSuperAdminUserAccount());
        sysUser.setUserNickname(PermissionUtils.getSuperAdminNickname());
        sysUser.setSalt(PermissionUtils.getSuperAdminUserSalt());
        sysUser.setUserGender(GenderEnum.MAN.getCode());
        return sysUser;
    }

}
